<?php

namespace App\Service\VendorClient\Shopjinque;

use App\Service\Code\Normal;
use App\Service\BaseService;
use Service\AppService\IdService;
use App\Service\TaskServer\TaskWorker;

/**
 * @author hj
 * 金雀oms供应商
 */
class ShopjinqueApiClient extends BaseService {
    //供应商编号
    const SUPPLIER_CODE = 'shopjinque';

    //配置文件
    private $config = [];

    public function __construct($apiBody = []) {
        $this->config = $apiBody;
    }

    /**
     * 创建订单
     * @param array $params
     * @return array
     */
    public function createOrder($param = []) {
        if (empty($param['supplierOrder']) || empty($param['orderGoods']) || empty($param['order']) || empty($param['binfo'])) {
            return Normal::returnCode(Normal::FAIL, "except param supplierOrder or orderGoods or order or binfo");
        }
        $orderInfo = $param['supplierOrder'];
        $goodsList = $param['orderGoods'];
        $order     = $param['order'];
        $binfo     = $param['binfo'];
        $order_sn  = $orderInfo['supplier_dsn'];
        //支付流水号
        $pay_sn = $order['paySerial'] ?? $orderInfo['pay_sn'];
        //订单时间
        $order_time = $orderInfo['cd'] ? date('Y-m-d H:i:s', $orderInfo['cd']) : date('Y-m-d H:i:s', time());
        //支付时间
        $pay_time = isset($order['payTime']) && !empty($order['payTime']) ? date('Y-m-d H:i:s', $order['payTime']) : date('Y-m-d H:i:s', time());
        //运费分摊
        $deliver_money = $orderInfo['deliver_money'];
        //下单支付的时候支付信息
        $apply_extends = @json_decode($orderInfo['apply_extends'], true);
        //电商平台信息
        $enterpriseNum  = $apply_extends['enterpriseNum'] ?? '';
        $enterpriseName = $apply_extends['enterpriseName'] ?? '';
        $enterpriseNum  = $order['enterpriseNum'] ?? $enterpriseNum;
        $enterpriseName = $order['enterpriseName'] ?? $enterpriseName;
        //支付公司信息
        $payCommanyCode = $apply_extends['payCommanyCode'] ?? '';
        $payCommanyName = $apply_extends['payCommanyName'] ?? '';
        $payCommanyCode = $order['payCommanyCode'] ?? $payCommanyCode;
        $payCommanyName = $order['payCommanyName'] ?? $payCommanyName;
        //获取下单商品信息
        $palceOrderGoods    = [];
        $totalGoodsMoney    = '0.00';
        $goodsTotalMoney    = '0.00';
        $goodsTotalMoneyNot = '0.00';
        $wayTaxFee          = '0.00';
        foreach ($goodsList as $key => $item) {
            $tax_rate         = bcadd('1', (string)$item['tax_rate'], 4);
            $price            = $item['price'];
            $spec_num         = $item['spec_num'];
            $quantity         = $item['quantity'];
            $supplier_skucode = $item['supplier_skucode'];
            $goods_type       = $item['goods_type'];
            //实际购买数量(下单数量 X 起售数量)
            $buyAcount = $spec_num * $quantity;
            // if ($key == 0) {
            //     $singleDeliveryMoney = bcdiv((string)$deliver_money, (string)$quantity, 3);
            //     $singleDeliveryMoney = bcmul((string)$singleDeliveryMoney, (string)100, 1);
            //     $singleDeliveryMoney = bcdiv((string)ceil($singleDeliveryMoney), (string)100, 2);
            //     $price               = bcadd((string)$price, (string)$singleDeliveryMoney, 2);
            // }
            //不含税价格
            $singleGoodsPrice = bcdiv((string)$price, (string)$tax_rate, 3);
            $singleGoodsPrice = bcmul((string)$singleGoodsPrice, (string)100, 1);
            $singleGoodsPrice = bcdiv((string)ceil($singleGoodsPrice), (string)100, 2);
            //商品不含税总价
            $goodsTotalPrice = bcmul((string)$singleGoodsPrice, (string)$quantity, 2);
            //含税总价
            $goodsTotalPriceTax = bcmul((string)$price, (string)$quantity, 2);
            //税费
            $tax    = bcsub((string)$price, (string)$singleGoodsPrice, 2);
            $taxAll = bcmul((string)$tax, (string)$quantity, 2);

            //判断是不是保税订单
            // $taxAll = $goods_type == 1 ? $taxAll : 0;
            //不含税总金额
            $goodsTotalMoneyNot = bcadd((string)$goodsTotalMoneyNot, (string)$goodsTotalPrice, 2);
            //含税总金额
            $goodsTotalMoney = bcadd((string)$goodsTotalMoney, (string)$goodsTotalPriceTax, 2);
            //总税费
            $wayTaxFee = bcadd((string)$wayTaxFee, (string)$taxAll, 2);
            //下单商品组
            $goodsInfo         = [
                'saleOrderCode'     => $order_sn,//订单号
                'productNumberCode' => $item['supplier_skucode'],//货号
                // 'saleGoodsPrice'    => $price,//单价（元）(含税的)
                'saleGoodsPrice'    => $singleGoodsPrice,//单价（元）(不含税的)
                'saleNumber'        => $quantity,//数量
                // 'saleSubTotal'      => $goodsTotalPriceTax,//金额（元），单价*数量(含税的)
                'saleSubTotal'      => $goodsTotalPrice,//金额（元），单价*数量(不含税的)
                'currency'          => '142',//币制（142=人民币，116=日元）
            ];
            $palceOrderGoods[] = $goodsInfo;
        }
        //商品单价*数量+ 税金+运费-优惠金额=支付单实际申报金额
        $calOrderMoney = bcadd(bcadd($goodsTotalMoneyNot, $wayTaxFee, 2), (string)$deliver_money, 2);
        $couponFee    = $calOrderMoney > $orderInfo['real_total_money'] ? bcsub($calOrderMoney, $orderInfo['real_total_money'], 2) : '0.00';

        $requestParam = [
            'orderInfo' => [
                'dealerShopCode'    => $this->config['dealerShopCode'],//对应店铺编码,系统分配
                'saleOrderCode'     => $order_sn,//订单号
                'buyerAccount'      => $orderInfo['buyer_phone'],//买家账号
                'buyerNickName'     => $orderInfo['buyer_realname'],//买家昵称
                'province'          => $orderInfo['province'],//省
                'city'              => $orderInfo['city'],//市
                'district'          => $orderInfo['district'],//区
                'address'           => $orderInfo['receive_address'],//具体地址
                'receiverName'      => $orderInfo['receive_name'],//收件人
                'receiverPhone'     => $orderInfo['recveive_phone'],//联系电话
                'buyerName'         => $orderInfo['buyer_realname'],//真实姓名
                'idcard'            => $orderInfo['buyer_idcard'],//身份证号
                // 'orderPayment'      => $goodsTotalMoney,//订单金额（元）,订单内商品总价 (含税)
                'orderPayment'      => $goodsTotalMoneyNot,//订单金额（元）,订单内商品总价 （不含税）
                'postFee'           => $deliver_money,//运费（元），无则填“0”
                'discount'          => $couponFee,//优惠金额
                'taxFee'            => $wayTaxFee,//企业预先代扣的税款金额，无则填“0” 总税费
                'buyerPayment'      => $orderInfo['real_total_money'],//实付金额（元）,实际支付金额
                'current'           => '142',//币种（142=人民币，116=日元）
                'payCode'           => $payCommanyCode,//支付企业的海关注册登记编 号
                'payName'           => $payCommanyName,//支付企业在海关注册登记的 企业名称
                'paymentCode'       => $order['paySerial'] ?? $apply_extends['paySerial'],//支付单号
                'paymentOrderSeq'   => $order_sn,//支付订单号
                'createTime'        => $order_time,//下单时间（格式：yyyy-MM-dd HH:mm:ss)
                'payTime'           => $pay_time,//付款时间（格式：yyyy-MM-dd HH:mm:ss)
                'dedicatedLineCode' => $this->config['dedicatedLineCode'],//专线代码,业务提供
                'importExportFlag'  => 'I',//进出口标志（I/E）
                'declareType'       => 'CBD',//固定值:CBD
                'logisticsCode'     => $this->config['logisticsCode'],//快递公司编码,中通:ZTOINC;顺丰:SF
            ],
            'details'   => $palceOrderGoods,
            'services'  => []
        ];
        $data         = [
            'method' => 'createOrder',
            'data'   => $requestParam,
        ];
        $result       = $this->execute($data);
        if ($result['code'] != Normal::SUC) {
            return $result;
        }
        if (!isset($result['data']['Result']) || empty($result['data']['Result'])) {
            return Normal::returnCode(Normal::FAIL, "推送订单失败", $result);
        }
        if ($result['data']['Result'] == 'T') {
            return Normal::returnCode(Normal::SUC, "推送订单成功", $result);
        }

        $errMsg = json_encode($result,JSON_UNESCAPED_UNICODE);
        return Normal::returnCode(Normal::FAIL, "推送订单失败【{$errMsg}】");
    }

    /**
     * 获取取消订单
     */
    public function cancelOrder($params = []) {
        $queryParam = [
            'saleOrderCode' => $params['supplierOrder']['supplier_dsn'],//订单号
        ];
        $data       = [
            'method' => 'cancelOrder',
            'data'   => $queryParam,
        ];
        return $this->execute($data);
    }

    /**
     * 查询物流信息
     * @param array $param
     */
    public function queryOrderExpress( $params = [] ) {
        $queryParam = [
            'saleOrderCode' => $params['supplier_dsn']
        ];
        $data         = [
            'method' => 'queryExpress',
            'data'   => $queryParam,
        ];
        return $this->execute($data);
    }

    /**
     * CURL请求
     * @param $params
     * @return array
     */
    public function execute($param = []) {
        $method = $param['method'];
        $data   = $param['data'];
        if (!isset($this->config[$method])) {
            return Normal::returnCode(Normal::FAIL, "请求路由未设置");
        }
        if (empty($param['data'])) {
            return Normal::returnCode(Normal::FAIL, "数据不能为空");
        }
        $url = $this->config[$method];
        if (empty($url)) {
            return Normal::returnCode(Normal::FAIL, "接口地址不能为空");
        }
        if(in_array($method, ['cancelOrder', 'queryExpress'])){
            $url = $url . "?" . http_build_query($data);
            $data = [];
        }
        $parameter = [
            [
                'tag'    => self::SUPPLIER_CODE . '_' . $param['method'],
                'uid'    => IdService::instance()->getOtherID(),
                'url'    => $url,
                'data'   => $data,
                'method' => 'post',
                'format' => 'json',
                'header' => [
                    "Authorization: {$this->config['authorization']}",
                    "Content-Type: application/json",
                ],
            ],
        ];
        $resTask   = TaskWorker::instance()->addTask($parameter);
        $resTask   = current($resTask);
        $result    = @json_decode($resTask['response']['result'], true);
        if (isset($result['code']) && $result['code'] == 200) {
            return Normal::returnCode(Normal::SUC, "操作成功", $result);
        } else {
            $msg = $result['msg'] ?? '请求失败';
            return Normal::returnCode(Normal::FAIL, $msg);
        }
    }
}